package com.ruoyi.web.controller.module.mer;

import java.util.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.QRCodeUtilEx;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.system.domain.module.*;
import com.ruoyi.system.domain.module.location.City;
import com.ruoyi.system.domain.module.location.Province;
import com.ruoyi.system.domain.module.mer.*;
import com.ruoyi.system.domain.module.product.Product;
import com.ruoyi.system.domain.module.product.ProductType;
import com.ruoyi.system.domain.module.wx.UserMp;
import com.ruoyi.system.domain.module.wx.UserRegCashRecord;
import com.ruoyi.system.domain.module.wx.WxUser;
import com.ruoyi.system.domain.system.SysUserRole;
import com.ruoyi.system.service.module.*;
import com.ruoyi.system.service.module.location.CityService;
import com.ruoyi.system.service.module.location.ProvinceService;
import com.ruoyi.system.service.module.mer.*;
import com.ruoyi.system.service.module.product.IProductService;
import com.ruoyi.system.service.module.product.IProductTypeService;
import com.ruoyi.system.service.module.wx.IUserMpService;
import com.ruoyi.system.service.module.wx.IWxUserService;
import com.ruoyi.system.service.system.ISysUserRoleService;
import com.ruoyi.system.service.system.ISysUserService;
import com.ruoyi.web.controller.common.BaseController;
import lombok.RequiredArgsConstructor;
import javax.validation.constraints.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 服务商家Controller
 *
 * @author ruoyi
 * @date 2021-09-05
 */
@Validated
@Api(value = "服务商家控制器", tags = {"服务商家管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/module/mer")
public class MerController extends BaseController {

    private final IMerService merService;
	private final IMerUserService merUserService;
	private final IProductTypeService productTypeService;
	private final ISysUserService sysUserService;
	private final ISysUserRoleService sysUserRoleService;
	private final IProductService productService;
	private final IMerCouponService merCouponService;
	private final IWxUserService wxUserService;
	private final IUserMpService userMpService;
	private final IParameterService parameterService;
	private final IMerCategoryService merCategoryService;
	private final ProvinceService provinceService;
	private final CityService cityService;
	private final IAdBannerService adBannerService;

	@Value("${ruoyi.imgUrl}")
	private String imgUrl;

//	@Value("${ruoyi.imgUrlOss}")
//	private String imgUrlOss;

	@Value("${ruoyi.profile}")
	private String uploadPath;

    /**
     * 查询服务商家列表
     */
    @ApiOperation("查询服务商家列表")
    @PreAuthorize("@ss.hasPermi('module:mer:list')")
    @GetMapping("/list")
    public TableDataInfo<Mer> list(@Validated Mer mer) {
    	SysUser sysUser = getUser();
        QueryWrapper<Mer> qw = new QueryWrapper<>();
        Map<String,Object> mapRet = new HashMap<>();
        if(StrUtil.isNotEmpty(mer.getShopName())){
        	qw.like("shop_name",mer.getShopName())
				.or().like("leader_name",mer.getShopName())
				.or().like("telphone",mer.getShopName());
			mapRet.put("keyword",mer.getShopName());
		}
        if(mer.getIsPlatform() != null){
			qw.eq("is_platform",mer.getIsPlatform());
			mapRet.put("is_platform",mer.getIsPlatform());
		}


        if(mer.getCheckState() != null){
        	qw.eq("check_state",mer.getCheckState());
			mapRet.put("check_state",mer.getCheckState());
		}

        if(mer.getShopType() != null){
        	qw.eq("shop_type",mer.getShopType());
			mapRet.put("shop_type",mer.getShopType());
		}else {
			qw.eq("shop_type", 0);
			mapRet.put("shop_type",0);
		}

//		if(sysUser.getUserType() == 2){//物业公司
//			qw.eq("property_id",sysUser.getPropertyId());
//			mapRet.put("property_id",sysUser.getPropertyId());
//		} else if(sysUser.getUserType() == 3){//小区
//			qw.eq("estate_id",sysUser.getEstateId());
//			mapRet.put("estate_id",sysUser.getEstateId());
//		} else
		if (sysUser.getUserType() == 4){// 商家  只能看自己的
			qw.eq("id",sysUser.getMerId());
			mapRet.put("id",sysUser.getMerId());
		}else if(sysUser.getUserType() == 3){//小区
			qw.eq("estate_id",sysUser.getEstateId());
			mapRet.put("estate_id", sysUser.getEstateId());
		}else{
			if(mer.getEstateId() != null){
				qw.eq("estate_id",mer.getEstateId());
				mapRet.put("estate_id",mer.getEstateId());
			}
		}

		if(mer.getCateChildId() != null){
			qw.eq("cate_child_id",mer.getCateChildId());
			mapRet.put("cate_child_id",mer.getCateChildId());
		}

		if(StrUtil.isNotEmpty(mer.getBeginDate())){
			qw.between("create_time",mer.getBeginDate() + " 00:00:00",mer.getEndDate() + " 23:59:59");
			mapRet.put("begin_time", mer.getBeginDate() + " 00:00:00");
			mapRet.put("end_time", mer.getEndDate() + " 23:59:59");
		}
		qw.orderByDesc("id");

		TableDataInfo<Mer> td = new TableDataInfo<>();
		if (ObjectUtil.isNotEmpty(mer.getShopType())&&mer.getShopType()!=8){
			if(sysUser.getUserType() == 4){
				mapRet.put("sys_user_id",sysUser.getUserId());
				td = PageUtils.buildDataInfo(merService.selectMerListByUserId(PageUtils.buildPage(),mapRet));
			}else{
				td = PageUtils.buildDataInfo(merService.selectAllByListPage(PageUtils.buildPage(),mapRet));
			}
		}else {
			td = PageUtils.buildDataInfo(merService.selectMerListByUserId(PageUtils.buildPage(),mapRet));
		}
		if (td.getRows().size()==0){
			td = PageUtils.buildDataInfo(merService.selectAllByListPage(PageUtils.buildPage(),mapRet));
		}

        List<Mer> list = td.getRows();
		list.forEach(mer1 -> {
			if(StrUtil.isNotEmpty(mer1.getShopLogo())){
				mer1.setShopLogoPath(imgUrl + mer1.getShopLogo());
			}else{
				mer1.setShopLogoPath("");
			}
			if(StrUtil.isNotEmpty(mer1.getQrCode())){
				mer1.setQrCode(imgUrl + mer1.getQrCode());
			}

			QueryWrapper<Product> qwPro = new QueryWrapper<>();
			qwPro.eq("mer_id",mer1.getId());
			qwPro.eq("is_show",1);
			long productCount = productService.count(qwPro);
			mer1.setProductCount(productCount);


			QueryWrapper<MerCoupon> qwCoupon = new QueryWrapper<>();
			qwCoupon.eq("mer_id",mer1.getId());
			long couponCount = merCouponService.count(qwCoupon);
			mer1.setCouponCount(couponCount);

			mer1.setUserMpCount(0);
			List<UserMp> userMps = userMpService.selectUserMpList(mer1.getId());
			if(CollUtil.isNotEmpty(userMps)){
				mer1.setUserMpCount(userMps.size());
			}

		});
		Map<String,Object> map = new HashMap<>();
		map.put("user_type",sysUser.getUserType());
		td.setOtherData(map);
        return td;
    }


	/**
	 * 查询服务商家列表
	 */
	@ApiOperation("查询服务商家列表")
	@GetMapping("/listNoPage")
	public AjaxResult listNoPage(@Validated Mer mer) {
		QueryWrapper<Mer> qw = new QueryWrapper<>();
		if(StrUtil.isNotEmpty(mer.getShopName())){
			qw.like("mer_name",mer.getShopName());
		}
		if(mer.getCateChildId()!=null){
			qw.eq("cate_child_id",mer.getCateChildId());
		}
		if(mer.getShopType()!=null){
			qw.eq("shop_type",mer.getShopType());
		}else {
			qw.eq("shop_type", 0);
		}

		List<Mer> list = merService.list(qw);
		list.forEach(mer1 -> {
			if(StrUtil.isNotEmpty(mer1.getShopLogo())){
				mer1.setShopLogoPath(imgUrl + mer1.getShopLogo());
			}else{
				mer1.setShopLogoPath("");
			}
			if(mer.getIsShowProduct() == null || mer.getIsShowProduct() == 1){
				QueryWrapper<Product> qwPro = new QueryWrapper<>();
				qwPro.eq("mer_id",mer1.getId());
				qwPro.eq("is_show",1);
				long productCount = productService.count(qwPro);
				mer1.setProductCount(productCount);
			}
		});
		return AjaxResult.success(list);
	}


	/**
	 * 查询服务商家列表
	 */
	@ApiOperation("查询服务商家列表")
	@GetMapping("/listByUserId")
	public AjaxResult listByUserId(@Validated Mer mer) {
		SysUser sysUser = getUser();
		Map<String,Object> map = new HashMap<>();
		map.put("sys_user_id",sysUser.getUserId());
		List<Mer> list = merService.selectMerListByUserId(map);
		list.forEach(mer1 -> {
			if(StrUtil.isNotEmpty(mer1.getShopLogo())){
				mer1.setShopLogoPath(imgUrl + mer1.getShopLogo());
			}else{
				mer1.setShopLogoPath("");
			}
//			QueryWrapper<Product> qwPro = new QueryWrapper<>();
//			qwPro.eq("mer_id",mer1.getId());
//			qwPro.eq("is_show",1);
//			long productCount = productService.count(qwPro);
//			mer1.setProductCount(productCount);
		});
		return AjaxResult.success(list);
	}

	/**
     * 获取服务商家详细信息
     */
    @ApiOperation("获取服务商家详细信息")
    @PreAuthorize("@ss.hasPermi('module:mer:query')")
    @GetMapping("/{id}")
    public AjaxResult<Mer> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        Mer mer = merService.getById(id);
        if(mer!=null){

			String[] areas = {String.valueOf(mer.getProvId()), String.valueOf(mer.getCityId()), String.valueOf(mer.getDistrictId())};
			mer.setProvinceArray(areas);

			if(StrUtil.isNotEmpty(mer.getShopLogo())){
                mer.setShopLogoPath(imgUrl + mer.getShopLogo());
            }else{
                mer.setShopLogoPath("");
            }

			if(StrUtil.isNotEmpty(mer.getCodeImg())){
				mer.setCodeImgPath(imgUrl + mer.getCodeImg());
			}else{
				mer.setCodeImgPath("");
			}

			List<Integer> cateIds = new ArrayList<>();
			QueryWrapper<MerCategory> qwC = new QueryWrapper<>();
			qwC.eq("mer_id",mer.getId());
			List<MerCategory> categories = merCategoryService.list(qwC);
			if(CollUtil.isNotEmpty(categories)) {
				for (MerCategory category : categories) {
					cateIds.add(category.getCateChildId());
				}
			}
			mer.setCateChildIds(cateIds);



			if(StrUtil.isNotEmpty(mer.getIdCardImgBefore())){
				mer.setIdCardImgBeforePath(imgUrl + mer.getIdCardImgBefore());
			}
			if(StrUtil.isNotEmpty(mer.getIdCardImgAfter())){
				mer.setIdCardImgAfterPath(imgUrl + mer.getIdCardImgAfter());
			}

			if(StrUtil.isNotEmpty(mer.getSignImg())){
				mer.setSignImgPath(imgUrl + mer.getSignImg());
			}

//			List<String> listHeTong = new ArrayList<>();
//			if(StrUtil.isNotEmpty(mer.getHeTongPic())){
//				String[] s = mer.getHeTongPic().split(",");
//				for (String ss : s){
//					listHeTong.add(imgUrl + ss);
//				}
//			}
//			mer.setHeTongPics(listHeTong);
		}
        return AjaxResult.success(mer);
    }

    /**
     * 新增服务商家
     */
    @ApiOperation("新增服务商家")
    @PreAuthorize("@ss.hasPermi('module:mer:add')")
    @Log(title = "服务商家", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping()
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody Mer mer) {
		boolean bl = false;
    	try{
			String shopNo = "M"+ new Date().getTime();
			mer.setShopNo(shopNo);
			mer.setCreateTime(new Date());
			mer.setAgId(0);
			if(mer.getShopType() == 1){
				//审核状态 0 -待审核 1-  审核通过 2 - 审核失败
				mer.setCheckState(1);
				mer.setCateId(0);
				mer.setCateChildId(0);
			}else{
				ProductType productType = productTypeService.findById(mer.getCateChildId());
				if(productType != null){
					ProductType productTypeParent = productTypeService.findById(productType.getParentId());
					if(productTypeParent != null){
						mer.setCateId(productTypeParent.getId());
					}
				}
			}

			if(mer.getProvinceArray()!=null&&mer.getProvinceArray().length==3){

				Province province = provinceService.findById(mer.getProvinceArray()[0]);
				if(province!=null){
					mer.setProvName(province.getProvinceName());
					mer.setProvId(province.getId());
				}

				City city = cityService.findById(mer.getProvinceArray()[1]);
				if(city!=null){
					mer.setCityName(city.getCityName());
					mer.setCityId(city.getId());
				}
			}


			List<Integer> cateChilds = new ArrayList<>();
			QueryWrapper<MerCategory> qwCategory = new QueryWrapper<>();
			qwCategory.eq("mer_id",mer.getId());
			List<MerCategory> categories = merCategoryService.list(qwCategory);
			if(CollUtil.isNotEmpty(categories)){
				for (MerCategory category : categories){
					cateChilds.add(category.getCateChildId());
				}
			}
			mer.setCateChildIds(cateChilds);

			String fileName = "mer_qr_" + mer.getShopNo() + ".jpg";
			String content = "https://www.caihengyun.com/wxmini/mer/pay?no=" + mer.getShopNo();
			int upload_type = FileUploadUtils.TYPE_DEVICE_PHOTOS;
			System.out.println("content:  "+ content);
			String img_key = FileUploadUtils.getUploadPrefix(upload_type) + fileName;
			QRCodeUtilEx.createQrCodeImg(content, mer.getShopName(), null, uploadPath + "/" + img_key, true, fileName, upload_type);
			mer.setQrCode(img_key);
			bl = merService.save(mer);

			if(bl){
				if(StrUtil.isNotEmpty(mer.getTelphone())) {
					QueryWrapper<SysUser> qw = new QueryWrapper<>();
					qw.eq("user_name", mer.getTelphone());
					qw.last("limit 1");
					SysUser sysUser = sysUserService.getOne(qw);
					if (sysUser == null) {
						sysUser = new SysUser();
						sysUser.setRoleId(5);//商家管理员用户
						sysUser.setUserType(4);//商家用户
						sysUser.setUserName(mer.getTelphone());
						sysUser.setPassword(SecurityUtils.encryptPassword("123456"));
						sysUser.setMerId(mer.getId());
						sysUser.setNickName(mer.getLeaderName());
						sysUser.setPhoneNum(mer.getTelphone());
						sysUser.setSex("1");
						sysUser.setStatus("1");// 未审核通过 不能登录
						sysUser.setDelFlag("0");
						sysUser.setCreateTime(new Date());
						sysUserService.save(sysUser);
					}

					QueryWrapper<SysUserRole> qwRole = new QueryWrapper<>();
					qwRole.eq("user_id", sysUser.getUserId());
					qwRole.eq("role_id", 5);
					qwRole.last("limit 1");
					SysUserRole sysUserRole = sysUserRoleService.getOne(qwRole);
					if (sysUserRole == null) {
						sysUserRole = new SysUserRole();
						sysUserRole.setUserId(sysUser.getUserId());
						sysUserRole.setRoleId(5);
						sysUserRoleService.save(sysUserRole);
					}


					MerUser merUser = new MerUser();
//			merUser.setUserId(user.getId());
					merUser.setCreateTime(new Date());
					merUser.setMerId(mer.getId());
					merUser.setSysUserId(sysUser.getUserId());
//			merUser.setNickName(user.getNickName());
					merUser.setUserType(0);
					merUser.setState(1);
					merUser.setIsAdmin(1);
					merUserService.save(merUser);
				}
			}
		}catch (Exception e){
    		e.printStackTrace();
		}
        return toAjax(bl);
    }


	/**
	 * 重置二维码
	 */
	@Log(title = "重置二维码")
	@PostMapping("/resetQrCode")
	@ResponseBody
	@PreAuthorize("@ss.hasPermi('module:mer:edit')")
	public AjaxResult<Void> resetQrCode(@RequestBody Mer mer) {
		if(mer.getId()!=null){
			try{
				mer = merService.getById(mer.getId());
				if(mer != null){
					String fileName = "mer_qr_" + mer.getShopNo() + ".jpg";
					String content = "https://www.caihengyun.com/wxmini/mer/pay?no=" + mer.getShopNo();
					int upload_type = FileUploadUtils.TYPE_DEVICE_PHOTOS;
					System.out.println("content:  "+ content);
					String img_key = FileUploadUtils.getUploadPrefix(upload_type) + fileName;
					QRCodeUtilEx.createQrCodeImg(content, mer.getShopName(), null, uploadPath +"/"+img_key, true, fileName, upload_type);
					mer.setQrCode(img_key);
				}
			}catch (Exception ex){
				ex.printStackTrace();
			}
			if (merService.updateById(mer)) {
				return AjaxResult.success();
			}
		}
		return AjaxResult.error();
	}


    /**
     * 修改服务商家
     */
    @ApiOperation("修改服务商家")
    @PreAuthorize("@ss.hasPermi('module:mer:edit')")
    @Log(title = "服务商家", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody Mer mer) {
    	if(mer.getShopNo()==null){
			String shopNo = "M"+ new Date().getTime();
			mer.setShopNo(shopNo);
		}

		if(mer.getShopType() == 1){
			//审核状态 0 -待审核 1-  审核通过 2 - 审核失败
			mer.setCheckState(1);
			mer.setCateId(0);
			mer.setCateChildId(0);
		}else{
			ProductType productType = productTypeService.findById(mer.getCateChildId());
			if(productType!=null){
				ProductType productTypeParent = productTypeService.findById(productType.getParentId());
				if(productTypeParent!=null){
					mer.setCateId(productTypeParent.getId());
				}
			}
		}


		if(mer.getProvinceArray()!=null&&mer.getProvinceArray().length==3){

			Province province = provinceService.findById(mer.getProvinceArray()[0]);
			if(province!=null){
				mer.setProvName(province.getProvinceName());
				mer.setProvId(province.getId());
			}

			City city = cityService.findById(mer.getProvinceArray()[1]);
			if(city!=null){
				mer.setCityName(city.getCityName());
				mer.setCityId(city.getId());
			}
		}

		if(mer.getShopType() == 0){
			List<Integer> cateChildIds = mer.getCateChildIds();
			if(cateChildIds!=null){
				QueryWrapper<MerCategory> qwC = new QueryWrapper<>();
				qwC.eq("mer_id",mer.getId());
				List<MerCategory> categories = merCategoryService.list(qwC);
				if(CollUtil.isNotEmpty(categories)){
					for (MerCategory category :  categories){
						int isHas = 0;
						for (Integer id : cateChildIds){
							if (id.intValue() == category.getCateChildId().intValue()) {
								isHas = 1;
								break;
							}
						}
						if(isHas == 0){
							merCategoryService.removeById(category.getId());
						}
					}
				}

				for (Integer childId : cateChildIds){
					QueryWrapper<MerCategory> qw = new QueryWrapper<>();
					qw.eq("mer_id",mer.getId());
					qw.eq("cate_child_id",childId);
					qw.last("limit 1");
					MerCategory merCategory = merCategoryService.getOne(qw);
					if(merCategory == null){
						merCategory = new MerCategory();
						merCategory.setMerId(mer.getId());
						merCategory.setCateId(2);
						merCategory.setCateChildId(childId);
						merCategoryService.save(merCategory);
					}
				}
			}
		}


		if(mer.getIsCheck() == 1 && mer.getCheckState() == 1){
			QueryWrapper<MerUser> qw = new QueryWrapper<>();
			qw.eq("mer_id",mer.getId());
			qw.last("limit 1");
			MerUser merUser = merUserService.getOne(qw);
			if(merUser!=null){
				merUser.setState(1);
				merUserService.updateById(merUser);

				SysUser sysUser = sysUserService.selectUserById(merUser.getSysUserId());
				if(sysUser!=null){
					sysUser.setStatus("0");
					sysUserService.updateById(sysUser);
				}
			}
		}
		MerUser merUser = null;
		if(StrUtil.isNotEmpty(mer.getTelphone())){
			String[] phoneNum = mer.getTelphone().split(",");
			for (String phone : phoneNum){

				QueryWrapper<SysUser> qw = new QueryWrapper<>();
				qw.eq("user_name",phone);
				qw.last("limit 1");
				SysUser sysUser = sysUserService.getOne(qw);
				if(sysUser == null){
					sysUser = new SysUser();
					sysUser.setRoleId(5);//商家管理员用户
					sysUser.setUserType(4);//商家用户
					sysUser.setUserName(phone);
					sysUser.setPassword(SecurityUtils.encryptPassword("123456"));
					sysUser.setMerId(mer.getId());
					sysUser.setNickName(mer.getLeaderName());
					sysUser.setPhoneNum(phone);
					sysUser.setSex("1");
					sysUser.setStatus("1");// 未审核通过 不能登录
					sysUser.setDelFlag("0");
					sysUser.setCreateTime(new Date());
					sysUserService.save(sysUser);
				}

				if(sysUser != null){
					QueryWrapper<SysUserRole> qwRole = new QueryWrapper<>();
					qwRole.eq("user_id", sysUser.getUserId());
					qwRole.eq("role_id",5);
					qwRole.last("limit 1");
					SysUserRole sysUserRole = sysUserRoleService.getOne(qwRole);
					if(sysUserRole == null){
						sysUserRole = new SysUserRole();
						sysUserRole.setUserId(sysUser.getUserId());
						sysUserRole.setRoleId(5);
						sysUserRoleService.save(sysUserRole);
					}

					QueryWrapper<MerUser> qwMer = new QueryWrapper<>();
					qwMer.eq("sys_user_id",sysUser.getUserId());
					qwMer.eq("mer_id",mer.getId());
					qwMer.last("limit 1");
					merUser = merUserService.getOne(qwMer);
					if(merUser == null){
						merUser = new MerUser();
						merUser.setUserId(0);
						merUser.setCreateTime(new Date());
						merUser.setMerId(mer.getId());
						merUser.setSysUserId(sysUser.getUserId());
						//merUser.setNickName(user.getNickName());
						merUser.setUserType(0);
						merUser.setState(1);
						merUser.setIsAdmin(1);
						merUserService.save(merUser);
					}
				}
			}
		}
		boolean bl = merService.updateById(mer);
        return toAjax(bl ? 1 : 0);
    }

    /**
     * 删除服务商家
     */
    @ApiOperation("删除服务商家")
    @PreAuthorize("@ss.hasPermi('module:mer:remove')")
    @Log(title = "服务商家" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return toAjax(merService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
